package com.crm.system.service.impl.finishOrderProductManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractManager.CustomerContractDeveloper;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerProductDetailMemberCard;
import com.crm.model.entity.finishOrderProduct.AnewSendProduct;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.returnMoney.ReturnMoney;
import com.crm.model.entity.sendRoyaltyManager.OrderSendRoyalty;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.finishOrderProductManager.AnewSendFinishProductQO;
import com.crm.model.qo.finishOrderProductManager.FinishOrderProductQO;
import com.crm.model.vo.customerManager.CustomerProductDetailMemberCardRawDataVO;
import com.crm.model.vo.finishOrderProduct.*;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.orderManager.OrderActivityVO;
import com.crm.model.vo.returnMoney.AddFinishResultVO;
import com.crm.model.vo.returnMoney.ReturnMoneyVO;
import com.crm.redis.service.returnMoneyManager.ReturnMoneyRedisService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.contractManager.CustomerContractDeveloperDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.finishOrderProductManager.AnewSendFinishProductDbService;
import com.crm.service.finishOrderProductManager.FinishOrderProductDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.returnMoney.ReturnMoneyDbservice;
import com.crm.service.sendRoyaltyManager.SendRoyaltyDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.finishOrderProductManager.FinishOrderProductService;
import com.crm.system.service.returnMoney.ReturnMoneyService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @Author:chaifuyou
 * @Date: 2021/7/30 14:33
 */
@Service
@Slf4j
public class FinishOrderProductServiceImpl implements FinishOrderProductService {

    @Autowired
    private FinishOrderProductDbService finishOrderProductDbService;

    @Autowired
    private SendRoyaltyDbService sendRoyaltyDbService;

    @Autowired
    private ReturnMoneyService returnMoneyService;

    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;

    @Autowired
    private CustomerProductOrderDbService productOrderDbService;

    @Autowired
    private CustomerContractDbService contractDbService;

    @Autowired
    private AnewSendFinishProductDbService anewSendFinishProductDbService;

    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;

    @Autowired
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;

    @Autowired
    private ReturnMoneyRedisService returnMoneyRedisService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    private CustomerContractDeveloperDbService customerContractDeveloperDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    /**
     * 查询完成订单的产品
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<FinishOrderProductVO> selectFinishOrderProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder,FinishOrderProductQO qo) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                case "planDate":
                {
                    order.append("plan_date ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(qo.getDateType())) {
            if ("thisWeek".equals(qo.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(qo.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(qo.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(qo.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(qo.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        List<FinishOrderProductVO> retustList=finishOrderProductDbService.selectCustomerProductList(order.toString(),qo,dateUnit);
        PageInfo<FinishOrderProductVO> page =new PageInfo(retustList);
        return new DhPageInfo<FinishOrderProductVO>(page,retustList);
    }

    /**
     * 修改完成订单的产品信息
     * @param finishOrderProduct
     */
    @Override
    public Boolean updateFinishOrderProduct(FinishOrderProduct finishOrderProduct) {
        return finishOrderProductDbService.updateFinishOrderProduct(finishOrderProduct);
    }

    /**
     * 查询未发放提成的产品
     * @return
     */
    @Override
    public List<ExportFinishOrderProductVO> selectExportFinishOrderProduct(FinishOrderProductQO qo) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String companyId = null;
        if ("4".equals(userAccount.getDeptId())){
            companyId = userAccount.getCompanyId();
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(qo.getDateType())) {
            if ("thisWeek".equals(qo.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(qo.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(qo.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("topDay".equals(qo.getDateType())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(qo.getDateType())) {
                //今天
                dateUnit = 5;
            }
        }
        return finishOrderProductDbService.selectExportFinishOrderProduct(companyId,dateUnit);
    }

    /**
     * 导入产品提成发放
     * @param list
     * @return
     */
    @Override
    public JSONObject importOrderProductRoyalty(List<ExportFinishOrderProductVO> list) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //返回的结果集
        JSONObject jsonObject = new JSONObject();
        //导入数量
        int importNum = 0;
        //失败行数
        String importFailIdStr = "";

        for (int i=0;i<list.size();i++){
            boolean b = true;
            ExportFinishOrderProductVO importVO = list.get(i);
            //没有产品号
            if ("".equals(importVO.getFinishOrderProductNum()) || Objects.isNull(importVO.getFinishOrderProductNum())){
                //导入失败
                if (StringUtils.isBlank(importFailIdStr)) {
                    importFailIdStr = String.valueOf(i + 1);
                } else {
                    importFailIdStr = importFailIdStr + "," + String.valueOf(i + 1);
                }
                b=false;
            }
            //根据产品号查询当前产品录没录提成
            if (b){
                String status = finishOrderProductDbService.selectOrderProductRoyaltyStatus(importVO.getFinishOrderProductNum());
                if (b && "1".equals(status)){
                    //导入失败
                    if (StringUtils.isBlank(importFailIdStr)) {
                        importFailIdStr = String.valueOf(i + 1);
                    } else {
                        importFailIdStr = importFailIdStr + "," + String.valueOf(i + 1);
                    }
                    b=false;
                }
            }
            //提成金额不能为null 或 ""
            if ( b && (Objects.isNull(importVO.getRoyaltyMoney()) || "".equals(importVO.getRoyaltyMoney().toString()))){
                //导入失败
                if (StringUtils.isBlank(importFailIdStr)) {
                    importFailIdStr = String.valueOf(i + 1);
                } else {
                    importFailIdStr = importFailIdStr + "," + String.valueOf(i + 1);
                }
                b=false;
            }
            if (b){
                FinishOrderProductVO finishOrderProductVO = finishOrderProductDbService.selectFinishOrderProductByNumber(importVO.getFinishOrderProductNum());
                FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
                finishOrderProduct.setFinishOrderProductId(finishOrderProductVO.getFinishOrderProductId());
                finishOrderProduct.setRoyaltyStatus("1");
                finishOrderProduct.setRoyaltyMoney(importVO.getRoyaltyMoney());
                finishOrderProduct.setPerformanceConversionRatio(importVO.getRatio());
                finishOrderProduct.setGradeMoney(importVO.getGradeMoney());
                finishOrderProduct.setRoyaltyAccountId(userAccount.getAccountId());
                finishOrderProduct.setRoyaltyRecordTime(new Date());
                finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
                finishOrderProduct.setUpdateTm(new Date());
                b = finishOrderProductDbService.updateFinishOrderProduct(finishOrderProduct);
                if (b){
                    OrderSendRoyalty orderSendRoyalty = new OrderSendRoyalty();
                    orderSendRoyalty.setChsOrderSendRoyaltyId(CommonUtils.getGUID());
                    orderSendRoyalty.setProductId(finishOrderProductVO.getProductId());
                    orderSendRoyalty.setProductType(Integer.valueOf(finishOrderProductVO.getOrderDetailType()));
                    orderSendRoyalty.setProductFinalPrice(finishOrderProductVO.getProductFinalPrice());
                    orderSendRoyalty.setScoreMoney(finishOrderProductVO.getProductFinalPrice());
                    orderSendRoyalty.setScoreConvertRatio(importVO.getRatio());
                    orderSendRoyalty.setRoyaltyMoney(importVO.getRoyaltyMoney());
                    orderSendRoyalty.setCreatePeopleId(userAccount.getAccountId());
                    orderSendRoyalty.setCreateTm(new Date());
                    sendRoyaltyDbService.addSendRoyalty(orderSendRoyalty);
                    importNum += 1;
                }
            }
        }
        jsonObject.put("importCallNum", importNum);
        jsonObject.put("importFailIdStr", importFailIdStr);
        return jsonObject;
    }

    /**
     * 补发产品
     * @param orderId
     */
    @Override
    public void anewSendFinishProduct(String orderId) throws ParseException {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        /*List<String> orderIdList = productOrderDbService.selectAnewSendFinishOrderId();
        for (int i=0;i<orderIdList.size();i++){
            orderId = orderIdList.get(i);
            List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductList(orderId,0);
            CustomerProductOrder customerProductOrder = productOrderDbService.selectCustomerProductOrderById(orderId);
            CustomerContract customerContract = contractDbService.selectContractById(customerProductOrder.getContractId());
            if (finishList.size()>0){
                returnMoneyService.addFinishProductList(finishList,0,customerContract.getContractType());
            }
            //发放会员卡
            returnMoneyService.hairpin(orderId);
        }*/
        List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductList(orderId);
        CustomerProductOrder customerProductOrder = productOrderDbService.selectCustomerProductOrderById(orderId);
        CustomerContract customerContract = contractDbService.selectContractById(customerProductOrder.getContractId());
        ReturnMoney returnMoney = new ReturnMoney();
        List<ReturnMoneyVO> list = returnMoneyDbservice.selectOrderId(orderId);
        if (Objects.nonNull(list) && list.size() > 0){
            returnMoney.setArriveTime(list.get(0).getArriveTime());
        }
        Integer count = 0;
        if (finishList.size()>0){
            AddFinishResultVO addFinishResultVO = returnMoneyService.addFinishProductList(finishList,0,customerContract.getContractType(),returnMoney,3);
            count = addFinishResultVO.getCount();
        }
        AnewSendProduct anewSendProduct = new AnewSendProduct();
        anewSendProduct.setProductOrderId(orderId);
        anewSendProduct.setUpdatePeopleId(userAccount.getAccountId());
        anewSendProduct.setUpdateTm(new Date());
        anewSendFinishProductDbService.updateAnewSendFinishProduct(anewSendProduct);
        anewSendProduct.setAnewSendProductId(CommonUtils.getGUID());
        anewSendProduct.setCreatePeopleId(userAccount.getAccountId());
        anewSendProduct.setCreateTm(new Date());
        if (count == finishList.size()){
            anewSendProduct.setAnewSendStatus(1);
        }else {
            anewSendProduct.setAnewSendStatus(0);
        }
        anewSendFinishProductDbService.insertAnewSendFinishProductLog(anewSendProduct);
        //发放会员卡
        returnMoneyService.hairpin(orderId);
    }

    /**
     * 查询需要补发产品的信息
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<AnewSendFinishProductVO> selectAnewSendFinishProduct(AnewSendFinishProductQO qo, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "orderCompleteTm":
                {
                    order.append("o.order_complete_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(qo.getDataUnit())) {
            if ("topDay".equals(qo.getDataUnit())) {
                //昨天
                dateUnit = 4;
            }
            if ("day".equals(qo.getDataUnit())) {
                //今天
                dateUnit = 5;
            }
        }
        List<AnewSendFinishProductVO> retustList=finishOrderProductDbService.selectAnewSendFinishProduct(order.toString(),qo,dateUnit);
        PageInfo<AnewSendFinishProductVO> page =new PageInfo(retustList);
        return new DhPageInfo<AnewSendFinishProductVO>(page,retustList);
    }

    /**
     * 查询订单下产品
     * @param orderId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public DhPageInfo<FinishOrderProduct> selectFinishProduct(String orderId, Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductList(orderId);
        PageInfo<FinishOrderProduct> page =new PageInfo(finishList);
        return new DhPageInfo<FinishOrderProduct>(page,finishList);
    }

    /**
     * 计算历史数据，业绩
     */
    @Override
    public void anewCountRoyalty() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductRoyaltyIsNullList();
        for (int i=0;i<finishList.size();i++){
            BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishList.get(i).getProductCategories(),finishList.get(i).getProductId());
            finishList.get(i).setPerformanceConversionRatio(ratio);
            OrderActivityVO activityVO = customerProductOrderDetailDbService.selectActivityProductCount(finishList.get(i).getProductOrderDetailId());
            if (Objects.nonNull(activityVO)){
                if ("2".equals(finishList.get(i).getOrderDetailType()) && Integer.valueOf(activityVO.getProductCount()) > 0
                    && Objects.nonNull(activityVO.getActivityFinalPrice())){
                    finishList.get(i).setGradeMoney(activityVO.getActivityFinalPrice().divide(new BigDecimal(activityVO.getProductCount()),2).multiply(ratio));
                }
            }
            if ("1".equals(finishList.get(i).getOrderDetailType()) && Objects.nonNull(finishList.get(i).getProductFinalPrice())){
                if (Objects.isNull(ratio)){
                    ratio = new BigDecimal("0");
                }
                finishList.get(i).setGradeMoney(finishList.get(i).getProductFinalPrice().multiply(ratio));
            }
            finishList.get(i).setRoyaltyStatus("1");
            finishList.get(i).setRoyaltyAccountId(userAccount.getAccountId());
            finishList.get(i).setCreatePeopleId(userAccount.getAccountId());
            finishList.get(i).setCreateTm(new Date());
            finishOrderProductDbService.updateFinishOrderProduct(finishList.get(i));
        }
    }

    @Override
    public void testFinish() {
        List<FinishOrderProductVO> finishVO = finishOrderProductDbService.selecttestFinishList();
        for (int i=0;i<finishVO.size();i++){
            Date arriveTime = returnMoneyDbservice.selectOrderMaxArriveTime(finishVO.get(i).getProductOrderId());
            if (Objects.nonNull(arriveTime) && Objects.nonNull(finishVO.get(i).getCompanyId()) && Objects.nonNull(finishVO.get(i).getGradeMoney())){
                returnMoneyRedisService.returnMoneyToRedis(finishVO.get(i).getCompanyId(),finishVO.get(i).getGradeMoney(),new BigDecimal("0"),arriveTime);
            }
        }
        List<ReturnMoneyVO> list = returnMoneyDbservice.testReturnMoenyList();
        for (int i=0;i<list.size();i++){
            if (Objects.nonNull(list.get(i).getArriveMoney())){
                returnMoneyRedisService.returnMoneyToRedis(list.get(i).getFilialeId(),new BigDecimal("0"),list.get(i).getArriveMoney(),list.get(i).getArriveTime());
            }
        }
    }

    /**
     * 同步finish表合同编号订单编号客户名称
     * @return
     */
    @Override
    public void synOrderNumber() {
        List<FinishOrderProductVO> finishVO = finishOrderProductDbService.selectOrderNumberIsNull();
        for (int i=0;i<finishVO.size();i++){
            FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
            CustomerProductOrder order = productOrderDbService.selectCustomerProductOrderById(finishVO.get(i).getProductOrderId());
            if (Objects.nonNull(order)){
                finishOrderProduct.setFinishOrderProductId(finishVO.get(i).getFinishOrderProductId());
                finishOrderProduct.setOrderNumber(order.getOrderNumber());
                CustomerContract customerContract = contractDbService.selectContractById(order.getContractId());
                if (Objects.nonNull(customerContract)){
                    finishOrderProduct.setContractNumber(customerContract.getContractNumber());
                }
                Customer customer = customerDbService.selectCustomerById(order.getCustomerId());
                if (Objects.nonNull(customer)){
                    finishOrderProduct.setCustomerName(customer.getCustomerName());
                }
                finishOrderProductDbService.updateFinishOrderProduct(finishOrderProduct);
            }
        }
    }

    /**
     * 拆分历史合作合同产品
     */
    @Override
    public void partCooperationContractProduct() {
        List<String> list = customerContractDeveloperDbService.selectCustomerContractDeveloperHistoryContractIdList();
        for (int i=0;i<list.size();i++){
            CustomerProductOrder order = productOrderDbService.selectCustomerProductOrderById(list.get(i));
            List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(order.getContractId());
            List<FinishOrderProduct>  finishList = finishOrderProductDbService.selectCustomerProductListByOrderId(list.get(i),"1");
            for (int k=0;k<finishList.size();k++){
                FinishOrderProduct finishOrderProduct = finishList.get(k);
                for (int d=0;d<developerList.size();d++){
                    UserAccount developerUser = userAccountDbService.selectUserAccountByUserId(developerList.get(d).getCoDeveloper());
                    if (Objects.isNull(developerUser) || Objects.isNull(developerUser.getAccountId())){
                        developerUser = userAccountDbService.selectUserAccountByAccountId(developerList.get(d).getCoDeveloper());
                    }
                    //判断合作开发主从
                    if (developerUser.getAccountId().equals(order.getCreatePeopleId())){
                        finishOrderProduct.setCooperateType("1");
                    }else {
                        finishOrderProduct.setCooperateType("2");
                    }
                    if ("2".equals(finishOrderProduct.getCooperateType())){
                        finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                    }
                    //比例
                    BigDecimal partRatio = new BigDecimal("0");
                    if(!(new BigDecimal("0").equals(developerList.get(d).getAllocationMount()) || new BigDecimal("0.00").equals(developerList.get(d).getAllocationMount()))
                            && !(new BigDecimal("0").equals(order.getOrderActualTotalAmount()) || new BigDecimal("0.00").equals(order.getOrderActualTotalAmount()))){
                        //比例
                        partRatio = developerList.get(d).getAllocationMount().divide(order.getOrderActualTotalAmount(),2,BigDecimal.ROUND_DOWN);
                    }
                    //拆分业绩金额
                    if (Objects.nonNull(finishOrderProduct.getGradeMoney())
                            && !new BigDecimal("0") .equals(finishOrderProduct.getGradeMoney()) && !new BigDecimal("0.00") .equals(finishOrderProduct.getGradeMoney())){
                        finishOrderProduct.setPartGradeMoney(finishOrderProduct.getGradeMoney().multiply(partRatio));
                    }
                    //拆分产品成交价
                    if (Objects.nonNull(finishOrderProduct.getProductFinalPrice())
                            && !new BigDecimal("0") .equals(finishOrderProduct.getProductFinalPrice()) && !new BigDecimal("0.00") .equals(finishOrderProduct.getProductFinalPrice())){
                        finishOrderProduct.setProductPartFinalPrice(finishOrderProduct.getProductFinalPrice().multiply(partRatio));
                    }
                    finishOrderProduct.setUpdateTm(new Date());
                    finishOrderProductDbService.updateFinishOrderProduct(finishOrderProduct);
                }

            }
        }
    }

    /**
     * 通过finishId查询finsh产品数据
     * @param finishOrderProductId 订单完成产品id
     * @return
     */
    @Override
    public FinishOrderProduct selectFinishOrderProductById(String finishOrderProductId) {
        return finishOrderProductDbService.selectFinishOrderProductById(finishOrderProductId);
    }

    /**
     * 查询订单下的finish表数据（不含赠品）
     * @param orderId
     * @return
     */
    @Override
    public DhPageInfo<FinishOrderProductVO> selectOrderFinishProduct(String orderId,Integer pageIndex,Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        Integer type = null;
        CustomerProductOrder order = productOrderDbService.selectProductOrderById(orderId);
        if (Objects.nonNull(order.getOrderSurcharge())
                && new BigDecimal("0").compareTo(order.getOrderSurcharge()) == -1){
            type = 1;
        }
        List<FinishOrderProductVO> resultList=finishOrderProductDbService.selectOrderFinishProduct(orderId,type);
        for (int i=0;i<resultList.size();i++){
            BigDecimal big = new BigDecimal("0");
            if (Objects.isNull(resultList.get(i).getFinishOrderProductId()) && type == 1
                    && "附加费用".equals(resultList.get(i).getProductName()) && "0001".equals(resultList.get(i).getFinishOrderProductNum())){
                big = returnMoneyDbservice.selectOrderSurchargeCount(resultList.get(i).getProductOrderId());
            }else {
                big = returnMoneyDbservice.selectOrderProductReturnMoneyCount(resultList.get(i).getFinishOrderProductId(),orderId);
            }
            if (Objects.isNull(big)){
                big = new BigDecimal("0");
            }
            resultList.get(i).setPaidMoney(big);
            resultList.get(i).setResidueMoney(resultList.get(i).getProductFinalPrice().subtract(big));
            //根据订单id 、 产品号 查询预回款金额
            BigDecimal productPreReturnMoney = returnMoneyDbservice.queryPreReturnMoneyTotal(orderId, resultList.get(i).getFinishOrderProductNum());
            resultList.get(i).setProductPreReturnMoney(productPreReturnMoney);
        }
        PageInfo<FinishOrderProductVO> page =new PageInfo(resultList);
        return new DhPageInfo<FinishOrderProductVO>(page,resultList);

    }

    /**
     * 查询余额支付的订单下的产品（不含赠品）
     * @param customerId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public DhPageInfo<FinishOrderProductVO> selectBalanceOrderFinishProduct(String customerId, Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<FinishOrderProductVO> resultList=finishOrderProductDbService.selectBalanceOrderFinishProduct(customerId);
        PageInfo<FinishOrderProductVO> page =new PageInfo(resultList);
        return new DhPageInfo<FinishOrderProductVO>(page,resultList);
    }

    /**
     * 同步旧订单产品号
     */
    @Override
    public void updateOldFinishProductNum() {
        List<CustomerProductOrderVO> list = productOrderDbService.selectCustomerAllOrder("2");
        for (int i=0;i<list.size();i++){
            List<FinishOrderProductVO> finishNumberList = finishOrderProductDbService.selectFinishNumberByOrderIdAndProduct(list.get(i).getProductOrderId());
            //for (int k=0;k<finishNumberList.size();k++){
                    List<FinishOrderProduct> finishOrderProduct=finishOrderProductDbService.selectFinishByOrderIdAndProductNumber(list.get(i).getProductOrderId(),null);
                    for (int p=0;p<finishOrderProduct.size();p++){
                        FinishOrderProduct finish = finishOrderProduct.get(p);
                        System.out.println("pppp -----    "+ p);
                        finish.setFinishOrderProductNum(finishNumberList.get(p).getFinishOrderProductNum());
                        finishOrderProductDbService.updateFinishOrderProduct(finish);
                    }
            //}
        }
    }


    @Override
    public void selectFinishProductNum(String orderId) {
        Map map = new HashMap();
        List<FinishOrderProductVO> list = finishOrderProductDbService.selectFinish19(orderId,null);
        for (int i=0;i<list.size();i++){
            map.put(list.get(i).getProductId(),list.get(i));
        }
        List<FinishOrderProductVO> finishNumberList = new ArrayList();
        for (Object finishOrderProductVO:map.values()){
            ObjectMapper objectMapper = new ObjectMapper();
            FinishOrderProductVO zfsp = objectMapper.convertValue(finishOrderProductVO, FinishOrderProductVO.class);
            finishNumberList.add(zfsp);
        }
        for (int k=0;k<finishNumberList.size();k++) {
                List<FinishOrderProductVO> list1 = finishOrderProductDbService.selectFinish19(orderId, finishNumberList.get(k).getProductId());
                List<FinishOrderProduct> finishOrderProduct = finishOrderProductDbService.selectFinishByOrderIdAndProductNumber(orderId, finishNumberList.get(k).getProductId());
                for (int p = 0; p < list1.size(); p++) {
                    FinishOrderProduct finish = finishOrderProduct.get(p);
                    System.out.println("pppp -----    " + p);
                    finish.setFinishOrderProductNum(list1.get(p).getFinishOrderProductNum());
                    finishOrderProductDbService.updateFinishOrderProduct(finish);
                }
        }

    }

    /**
     * opp客户购买产品
     * @param list
     * @return
     */
    @Override
    public List<ExportOppFinishProductVO> exportOppCustomerFinishProduct(List<ImportOppFinishProductVO> list) {
        List customerList = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            customerList.add(list.get(i).getCustomerName());
        }
        List<ExportOppFinishProductVO> result = finishOrderProductDbService.exportOppCustomerFinishProduct(customerList);
        return result;
    }

}
